package com.crawler.search.index.service.impl;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.crawler.search.index.service.ESIndexSaver;
import com.crawler.search.index.suffix.Suffixer;
import com.crawler.search.utils.ESIndexUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * ES索引操作实现
 *
 * @author zhangyonghui
 * @Class Name ESIndexSaverImpl
 * @Create In 下午3:50:26
 */
@Service("esIndexSaver")
public class ESIndexSaverImpl implements ESIndexSaver {

    @Autowired
    public ESIndexUtils esIndexUtils;

    private static Logger logger = LoggerFactory.getLogger(ESIndexSaverImpl.class);


    /**
     * 创建索引
     *
     * @param index
     * @param mapping
     * @return
     */
    @Override
    public boolean createIndex(String index, String mapping, Suffixer suffixer) {
        boolean isCreate = false;
        try {
            esIndexUtils.checkIndexAlias(index);
            isCreate = esIndexUtils.applyMapping(index, mapping, suffixer);
        } catch (Exception e) {
            logger.info("create index :{} error:{}", index, ExceptionUtil.getRootCause(e));
        }
        return isCreate;
    }


    /**
     * 删除索引
     *
     * @param index
     * @return
     */
    @Override
    public boolean deleteIndex(String index) {
        return esIndexUtils.deleteIndex(index);
    }


    /**
     * 更新索引
     *
     * @param index
     * @param mapping
     * @return
     */
    @Override
    public boolean updateIndex(String index, String mapping) {
        return esIndexUtils.updateMapping(index, mapping);
    }
}
